<?php
	/**
	 * 获取通用常量
	 * @param  [type] $key [description]
	 * @return [type]      [description]
	 */
	function config_value($key){
		$list = [
			'key'=>'config',
			//合同_打印控制 all（不限制）/success（生效后才可打印）
			'contract_print_control'=>'all',
			//合同_编号 留空（不限制）/ {data:ymd} 日期 {count:day}每天的数字 例如[['text','Rx'],['data','Ymd'],['count','day','4']]
			'contract_ordernumber_control'=>[],
			//支付二维码
			'contract_pay_url'=>'',
			//客户信息只有对应业务员可看（此权限高于客户保护期） true确认  false否
			'customer_only_show'=>false,
			//企业档案信息只有对应业务员可看 true确认 false否
			'company_file_only_show'=>false,
			//途狐管车接口
			'iot_tuhugc_appKey' => '',
			'iot_tuhugc_appsecret' => '',
			'iot_tuhugc_username' => '',
			//腾讯地图
			'QQMAPKEY'=>'OAZBZ-MA3WU-GSPVV-4ST4Y-CFVWQ-3FB3Q',
			//多合同模式 false 假 ，true 真
			'has_contract_temp'=>false,
			//填写客户所属区域 show 显示 hide隐藏 must必填
			'input_street_area' =>'hide',
			//街道监管者模式 true 开启 false关闭
			'power_street_supervise_role'=>false,
			//多收集公司 true 开启 false关闭  涉及区域：危废收集订单选择、修改
			'power_double_receipt_company'=>false,
			//新版微信模板消息 false 为老版本  true 为新版本
			'new_wechat_message_state'=>false,
			//公司所处区域的行政编码
			'map_city_polygon'=>'130900',


			//---------处置·创美 -----
			//服务费功能的开关 由业务员代理
			'switch_Rebate'=>false,//服务费功能开关 false 关，true开
			//合同挂账功能开关  由会计管理 （在危废收集订单，合同订单结算时，可选择挂账结算 和直接结算两种模式）
        	'switch_revenue_account_period'=>true,//挂账功能 false 关，true开   【涉及变更表结构 contract RAPListId】
        	//审批合同功能 如果开启后，会计结算合同将不会直接将状态改变为通过，还需要进行管理层审批【涉及表结构 approval Type=contract】
        	'switch_approval_contract'=>false,//审批功能 false 关，true开  

        	//----------云客系统（业务人员手机）------------
        	'yunke_switch'  => false,//功能开关
			'yunke_app_key' => '',//key 需要去官网申请 https://crm2.yunkecn.com/cms/settings/openApplication
		    'yunke_partnerId' => '',//用户id，用于识别调用人，大部分请求为平台分配的管理员id，个别接口需要传员工的用户id
		    'yunke_company' => '',//企业串码

		    //------------数企api-------------------
        	//电话呼叫中心 是否开启
			'call_center_switch'=>false,
			//电话呼叫中心key
			'call_center_app_key'=>'',
			//电话呼叫中心key
			'call_center_code'=>'',
			//数企api，将数企数据传输到本系统中，通过get设置传输密钥
			'self_api_key_shuqi'=>'asdfdsaf126556dfwe',


		];
		if(!isset($list[$key])){return false;}else{return isset($list[$key])?$list[$key]:'[no_config]';} 
	}
	/**
	 * 获取配置变量
	 * @return [type] [description]
	 */
	function get_config_value($key){
		$a='[no_config]';
		if(function_exists('private_config_value')){
			$a = private_config_value($key);
		}
		if($a==='[no_config]'){
			$a = config_value($key);
		}
		return $a;
	}

	//-----------------------通用方法------------------------------------
	/**
	 * 删除数组空值
	 * @param  [type] $arr [description]
	 * @return [type]      [description]
	 */
	function array_del_empty($arr){
		if(empty($arr)){
			return $arr;
		}
		foreach ($arr as $key => $value) {
			if(empty($value)){
				unset($arr[$key]);
			}
		}
		return $arr;
	}
	/**
     * 网址编码
     * @param  [type] $url [description]
     * @return [type]      [description]
     */
    function encodeURI($url) {
        $unescaped = array(
            '%2D'=>'-','%5F'=>'_','%2E'=>'.','%21'=>'!', '%7E'=>'~',
            '%2A'=>'*', '%27'=>"'", '%28'=>'(', '%29'=>')'
        );
        $reserved = array(
            '%3B'=>';','%2C'=>',','%2F'=>'/','%3F'=>'?','%3A'=>':',
            '%40'=>'@','%26'=>'&','%3D'=>'=','%2B'=>'+','%24'=>'$'
        );
        $score = array(
            '%23'=>'#'
        );
        return strtr(rawurlencode($url), array_merge($reserved,$unescaped,$score));
    }


	/**
	 * 判断是否为json
	 * @param  [type]  $string [description]
	 * @return boolean         [description]
	 */
	function json_array($string,$sb='') {
		if(!is_array($string)){
			$data = json_decode($string);
			if(json_last_error() == JSON_ERROR_NONE){
				$sb = json_decode($string,true);
				if(is_string($sb)){
					return $sb = json_decode($sb,true);
				}else{
					return $sb; 
				}
			}else{
				return moerr('没找到json数据');
			}
		}else{
			return $string;
		}
	}

	/**
	 * 小微到同步中心的重量
	 * @param  [type] $weight [description]
	 * @return [type]         [description]
	 */
	function get_xw_sync_weight($weight){
		switch (SYNC_WEIGHT) {
			case '克':
				$weight = bcmul($weight,1000,6);//bc math 乘法
				break;
			case '吨':
				$weight = bcdiv($weight,1000,6);
				break;
		}
		return $weight;
	}

	/**
	 * 同步中心到小微的重量
	 * @param  [type] $weight [description]
	 * @return [type]         [description]
	 */
	function get_sync_xw_weight($weight){
		switch (SYNC_WEIGHT) {
			case '克':
				$weight = $weight / 1000;
				break;
			case '吨':
				$weight = $weight * 1000;
				break;
		}
		return $weight;
	}
	/**
	 * 数组根据id格式化
 	 * 方便前端直接调用
	 * @param  [type]  $data   [description]
	 * @param  [type]  $key    [description]
	 * @param  boolean $simple [每个数组是否只有一个元素]
	 * @return [type]          [description]
	 */
	function arr_id_formate($data,$key,$simple=false){
		$nlist    = [];
		if(empty($data[0][$key])){
			return $data;
		}
        $sb       = $data[0][$key];
        $chillist = [];
        if(!$simple){
        	foreach ($data as $key2 => $value) {
        		 if ($sb == $value[$key]) {
	                $chillist[] = $value;
	            } else {
	                //把老数组推进去
	                $nlist[$sb] = $chillist;
	                //标记设置为新数组
	                $sb       = $value[$key];
	                $chillist = [$value];
	            }
        	}
        	//把老数组推进去
	        if(!empty($chillist)){
		        $nlist[$sb] = $chillist;
	        }
        }else{
        	foreach ($data as $key2 => $value) {
        		$nlist[$value[$key]] = $value;
        	}
        }

        $data = $nlist;
        return $data;
	}

	function getrolename($id=''){
		$data = ['101'=>'产废管理员',
		         '106'=>'运输管理员',
				 '107'=>'运输收集员',
				 '201'=>'业务员',
				 '202'=>'库管',
				 '203'=>'会计',
				 '204'=>'业务经理',
				 '205'=>'股东',
				 '206'=>'省平台操作员',
				 '207'=>'监管单位',
				 '208'=>'调度者',
				 '301'=>'工厂管理员',
				 '302'=>'工厂员工',
				 '401'=>'代理商管理员',
				 '402'=>'代理商员工',
			];
		if(empty($id)){
			return $data;
		}else if(empty($data[$id])){
			return '暂无角色权限';
		}else{
			return $data[$id];
		}
	}

	function init_post($data){
		if(!empty($data['ids'])){
			$data['ids'] = explode(',',$data['ids']);
			$data['ids'] = array_unique($data['ids']);
		}
		return $data;
	}
	/**
	 * 构造where语句
	 * @param  [type] $data      [description]
	 * @param  array  $changearr [修改指定字段名称]
	 * @return [type]            [description]
	 */
	function init_where($data,$changearr = []){
		if(empty($data['where'])){
			$data['where'] = [];
		}
		if(!empty($data['bussid'])){
			if(!isset($changearr['bussid']) ||(isset($changearr['bussid'])&&!$changearr['bussid']==false)){
				$data['where'][]=['BussinessId',(int)$data['bussid']];
			}
		}
		if(!empty($data['compid'])){
			$data['where'][]=['CompanyId',(int)$data['compid']];
		}
		if(isset($data['state'])&&(int)$data['state']!==-1){
			$lsfile = 'State';
			//改变状态字段
			if(!empty($changearr['state'])){
				$lsfile = $changearr['state'];
			}
			$data['where'][]=[$lsfile,(int)$data['state']];
		}

		//时间字段
		if(!isset($changearr['time'])){
			if(isset($data['Type'])){
				$filed = get_time_filed($data['Type']);
			}
		}else{
			$filed = $changearr['time'];
		}
		if(!empty($data['startValue'])){
			if($filed!==false){
				$data['where'][]=[$filed,'>=',$data['startValue']];
			}
		}
		if(!empty($data['endValue'])){
			$data['endValue'] = date('Y-m-d',strtotime($data['endValue'])).' 24:00';
			if($filed!==false){
				$data['where'][]=[$filed,'<=',$data['endValue']];
			}
		}
		if(!empty($data['startValue'])){
			$data['startValue'] = date('Y-m-d',strtotime($data['startValue'])).' 00:00';
			if($filed!==false){
				$data['where'][]=[$filed,'>=',$data['startValue']];
			}
		}
		return $data;
	}
	/**
	 * model执行where
	 * @param  [type] $data  [description]
	 * @param  [type] $rdata [description]
	 * @return [type]        [description]
	 */
	function come_model_option($data,$rdata,$is_page = true){

		$data['Type'] = empty($data['Type'])?'':$data['Type'];
		if(!empty($data['where'])){
            foreach ($data['where'] as $key => $value) {
                switch (count($value)) {
                    case 1:
                        $rdata = $rdata->where($value[0]);
                        break;
                    case 2:
                        $rdata = $rdata->where($value[0],$value[1]);
                        break;
                    case 3:
                       $rdata = $rdata->where($value[0],$value[1],$value[2]);
                        break;
                    default:
                        moerr('系统错误');
                        break;
                }

            }
        }
        $count = $rdata->count();
        //修复不知道哪里出了问题，查询count以后就会直接打印sql语句而不是内容
        if(gettype($rdata->count())=='string'){
        	$rdata = $rdata->fetchSql(false);
        }
        if(!empty($data['limit'])){
        	if(is_array($data['limit'])){
        		$rdata = $rdata->limit($data['limit'][0],$data['limit'][1]);
        	}else{
            	$rdata = $rdata->limit($data['limit']);
        	}
        }else{
        	if(empty($data['p_limit'])){
        		$limit = PUBLICSELECTLIMIT;
        	}else{
        		$limit = $data['p_limit'];
        	}
        	if ($is_page) {
	        	$data['pageindex'] = empty($data['pageindex'])?1:$data['pageindex'];
		        $data['count'] = ceil($count/$limit);
		        $rdata = $rdata->limit($limit)->page($data['pageindex']);
	        }
        }

        if(empty($data['order'])){
            $rdata = $rdata->order(get_time_filed($data['Type']).' desc');
        }else{
            $rdata = $rdata->order($data['order']);
        }

        if(!empty($data['field'])){
            $rdata = $rdata->field($data['field']);
        }
        return ['rdata'=>$rdata,'data'=>$data,'count'=>$count];
	}
	/**
	 * 获取距离的filed
	 * @param  [type] $lat [description]
	 * @param  [type] $lon [description]
	 * @return [type]      [description]
	 */
	function str_distance($lat,$lon){
		return "(6378.138 * 2 * asin(sqrt(pow(sin((lat * pi() / 180 - ".$lat." * pi() / 180) / 2),2) + cos(lat * pi() / 180) * cos(".$lat." * pi() / 180) * pow(sin((lon * pi() / 180 - ".$lon." * pi() / 180) / 2),2))) * 1000) as distance";
	}
	/**
	 * 根据type转换为时间判定字段
	 * @param  [type] $type [description]
	 * @return [type]       [description]
	 */
	function get_time_filed($type){
		$data=['manaorderhawa'=>'UpTime','ware'=>'WarehouseTime','receipt'=>'WarehouseTime','orderhawabuss'=>'UpTime','disposalsite'=>'CreateTime','company'=>'CreateTime','contract'=>'CreateTime','costview'=>'PayTime','cost'=>'UpTime','quot'=>'SetTime','customer'=>'Addtime','SyncCenter'=>'CreateTime','CompanyTouch'=>'TouchTime'];
		if(empty($data[$type])){
			return 'UpTime';
		}
		return $data[$type];
	}
	/**
	 * 获取数组指定的id
	 * @param  [type] $ndata    [ 数据]
	 * @param  [type] $filename 字段名
	 * @param  string $str1     外循环list名称
	 * @param  string $str2     内循环list名称
	 * @return [type]           [description]
	 */
	function  get_array_id($ndata,$filename,$str1='',$str2='',$uniq = true){
		$goodid = [];
        if(empty($str2)){
        	if(empty($str1)){
        		foreach ($ndata as $key => $value) {
        			$goodid[] = $value[$filename];
        		}
        	}else{
        		foreach ($ndata[$str1] as $key => $value) {
		            $goodid[] = $value[$filename];
		        }
        	}
        }else{
        	foreach ($ndata[$str1] as $key => $value) {
	            foreach ($value[$str2] as $key2 => $value2) {
	                $goodid[] = $value2[$filename];
	            }
	        }
        }
        if($uniq){
	        return array_unique($goodid);
        }else{
        	return $goodid;
        }
	}

	function moerr($str='缺少重要参数',$url='',$options=''){
		myerr($str,$url,$options)->send();
        exit;
	}
	function myok($msg='操作成功',$url='',$options=''){
		if(isset($msg['code'])&&isset($msg['msg'])){
			return json($msg);
		}
		return json(['code'=>true,'msg'=>$msg,'options'=>$options,'url'=>$url]);
	}

	function myerr($msg='没有需要查询的数据',$url='',$options='',$jump=false){
		if(!$jump){
			if(isset($msg['code'])&&isset($msg['msg'])){
				return json($msg);
			}
		  	return json(['code'=>false,'msg'=>$msg,'options'=>$options,'url'=>$url]);
		}else{
			json(['code'=>false,'msg'=>$msg,'options'=>$options,'url'=>$url])->send();
			exit;
		}
	}

	function serr($msg='没有需要查询的数据',$url='',$options=''){
	  	  	return ['code'=>false,'msg'=>$msg,'options'=>$options,'url'=>$url];
	}
	function sok($msg='没有需要查询的数据',$url='',$options=''){
	  	  	return ['code'=>true,'msg'=>$msg,'options'=>$options,'url'=>$url];
	}

	function selfapi($url,$data=''){
		header('Access-Control-Allow-Origin: *');
		header("Access-Control-Allow-Headers:Origin, X-Requested-With, Content-Type, Accept");
		header('Access-Control-Allow-Methods: POST,GET');
		header('Access-Control-Allow-Credentials:true');
		if(!empty($data)){
			$data = json_encode($data);
		}
		$request = Request::instance();
	  	$curl = curl_init();
	  	curl_setopt($curl,CURLOPT_URL,$url);
	  	curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,FALSE);
	  	curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,FALSE);
	  	if(!empty($data)){
	  	  // dump($data);
	  	    curl_setopt($curl,CURLOPT_POST,1);
	  	    curl_setopt($curl,CURLOPT_POSTFIELDS,$data);
	  	}
	  	curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
	  	curl_setopt($curl, CURLOPT_HTTPHEADER, array(
	  	    'Content-Type: application/x-www-form-urlencoded',
	  	    'Content-Length: ' . strlen($data)
	  	));
	  	$output = curl_exec($curl);
	  	curl_close($curl);
	  	return json_decode($output,true);
	}

	function baiduapi($url,$data=''){
		$ch = curl_init();
		$options =  array(
		    CURLOPT_URL => $url,
		    CURLOPT_POST => true,
		    CURLOPT_RETURNTRANSFER => true,
		    CURLOPT_NOBODY => false,
		    CURLOPT_POSTFIELDS => http_build_query($data),
		    CURLOPT_HTTPHEADER => array('Content-Type: application/x-www-form-urlencoded'),
		);
		curl_setopt_array($ch, $options);
		$result = curl_exec($ch);
	  	curl_close($ch);
	  	return json_decode($result,true);
	}

	/**
	 * 验证是否全为前端数字数组
	 * @param  string  $value   待验证字符串
	 * @param  string  $str     验证字段名
	 * @param  boolean $auto    [是否自动处理]
	 * @param  string  $url     [description]
	 * @param  string  $options [description]
	 * @return [type]           [description]
	 */
	function vali_number_arr($value,$str='',$auto=true,$url='',$options=''){
		return public_vali('/^(\d+,)*\d+$/',$value,$str,$auto,$url,$options);
	}
	/**
	 * 公用验证方法
	 * @param  string  $match   正则
	 * @param  string  $value   需要验证数据
	 * @param  string  $str     [验证字段名]
	 * @param  boolean $auto    [默认直接返回处理数据]
	 * @param  string  $url     [description]
	 * @param  string  $options [description]
	 * @return [type]           [description]
	 */
	function public_vali($match,$value,$str='',$auto=true,$url='',$options=''){
		if(!$auto){
			if(preg_match($match, $value)==0){
				return serr($str.'参数错误');
			}else{
				return sok();
			}
		}
		if(preg_match('/^(\d+,)*\d+$/', $value)==0){
			return myerr($str.'参数错误',$url,$options,true);
		}
	}

	/**
	 * 获取行政区划
	 * @param  [type] $address [description]
	 * @return [type]          [description]
	 */
	function get_address_xzqh($address){
		$wz  = mb_strpos($address, COMPANYCITY)+mb_strlen(COMPANYCITY);
		$str = mb_substr($address,$wz);
		$qh  = ["市","县","区"];
		foreach ($qh as $key => $value) {
			$sb = mb_strpos($str, $value);
			if($sb!==false){
				return  mb_substr($str,0,$sb+mb_strlen($value));
			}
		}
		return '';
	}
	/**
     * 获取当月的第一天和最后一天
     */
    function getMonth($date)
    {
        $firstday = date('Y-m-01', strtotime($date));
        $lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));
        return array(strtotime($firstday),strtotime($lastday) + 24*60*60 -1);
    }
    /**
     * 获取本周第一天和最后一天
     */
    function getWeek($date)
    {
        $week = date('w',strtotime($date));
        $startTime = strtotime("$date -".($week ? $week - 1 : 6).' days');//本周第一天
        $overTime = $startTime + 86400*7 -1; //本周最后一天
        return [$startTime, $overTime];
    }
    /**
     * 计算两个经纬度之间的距离 单位km
     * @param float | string $lat1 纬度1
     * @param float | string $lng1 经度1
     * @param float | string $lat2 纬度2
     * @param float | string $lng2 经度2
     * @return float 两点距离 单位km
     **/
    function calculateDistance($lat1, $lng1, $lat2, $lng2) {
        // deg2rad()函数将角度转换为弧度
        $radLat1 = deg2rad($lat1);
        $radLat2 = deg2rad($lat2);
        $radLng1 = deg2rad($lng1);
        $radLng2 = deg2rad($lng2);
        $a       = $radLat1 - $radLat2;
        $b       = $radLng1 - $radLng2;
        $s       = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6371;
        return round($s, 1);
    }

	/**
	 * 将字符串中的Unicode转义序列(包括_Uxxxx和\uxxxx格式)转换为对应的中文字符
	 * 
	 * @param string $input 包含Unicode转义序列的字符串
	 * @return string 转换后的字符串
	 */
	function unicodeToChinese($input) {
	    // 统一转换函数
	    $convert = function($matches) {
	        $char = mb_convert_encoding(
	            '&#' . intval($matches[1], 16) . ';',
	            'UTF-8',
	            'HTML-ENTITIES'
	        );
	        return $char;
	    };
	    // 一次性处理所有格式：_Uxxxx 和 \uxxxx
	    $result = preg_replace_callback(
	        '/(_U|\\\\u)([0-9A-Fa-f]{4})/',
	        function($m) use ($convert) {
	            return $convert(['', $m[2]]);
	        },
	        $input
	    );
	    
	    // 特别处理可能残留的斜杠
	    return str_replace('\\', '', $result);
	}
